<template>
  <div class="course-list-container">

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <div class="filter-content">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程..."
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="filter-group">
          <el-select v-model="selectedCategory" placeholder="课程分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>

          <el-select v-model="selectedLevel" placeholder="难度等级" clearable>
            <el-option label="初级" value="beginner" />
            <el-option label="中级" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>

          <el-select v-model="selectedPrice" placeholder="价格区间" clearable>
            <el-option label="免费" value="free" />
            <el-option label="付费" value="paid" />
            <el-option label="0-50元" value="0-50" />
            <el-option label="50-100元" value="50-100" />
            <el-option label="100元以上" value="100+" />
          </el-select>

          <el-select v-model="sortBy" placeholder="排序方式" clearable>
            <el-option label="最新" value="newest" />
            <el-option label="最热" value="popular" />
            <el-option label="评分" value="rating" />
            <el-option label="价格升序" value="price_asc" />
            <el-option label="价格降序" value="price_desc" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="courses-section">
      <div class="section-header">
        <h2>全部课程</h2>
        <div class="result-count">
          共 {{ total }} 门课程
        </div>
      </div>

      <div v-if="loading" class="loading">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="courses.length === 0" class="empty">
        <el-empty description="暂无相关课程" />
      </div>

      <div v-else>
        <div class="courses-grid">
          <CourseCard
            v-for="course in courses"
            :key="course.id"
            :course="course"
            @click="$router.push(`/courses/${course.id}`)"
          />
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 48, 96]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { courseApi } from '@/api/course'
import CourseCard from '@/components/CourseCard.vue'
import { Search } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 筛选条件
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedLevel = ref('')
const selectedPrice = ref('')
const sortBy = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 数据
const courses = ref([])
const categories = ref([])
const loading = ref(false)

// 加载课程列表
const loadCourses = async () => {
  loading.value = true
  try {
    // 使用新的API接口
    const response = await courseApi.getCourseList()
    // 根据新的数据结构调整数据
    const data = response.data || response
    courses.value = Array.isArray(data) ? data : (data.records || data.list || [])
    total.value = Array.isArray(data) ? data.length : (data.total || courses.value.length)
    
    // 转换数据结构以适配CourseCard组件
    courses.value = courses.value.map(course => ({
      id: course.id,
      title: course.courseName || course.name,
      description: course.intro || course.description,
      cover: course.coverUrl,
      price: course.price || 0,
      studentCount: course.studentCount || 0,
      rating: course.rating || 0,
      tags: course.tags || []
    }))
  } catch (error) {
    console.error('加载课程失败:', error)
    ElMessage.error('加载课程失败')
  } finally {
    loading.value = false
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    // 这里应该调用分类相关的API
    // 暂时使用模拟数据
    categories.value = [
      { id: 1, name: '前端开发' },
      { id: 2, name: '后端开发' },
      { id: 3, name: '移动开发' },
      { id: 4, name: '数据库' },
      { id: 5, name: '云计算' }
    ]
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadCourses()
}

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadCourses()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadCourses()
}

// 监听路由参数
watch(
  () => route.query,
  (newQuery) => {
    searchKeyword.value = newQuery.search || ''
    selectedCategory.value = newQuery.category || ''
    selectedLevel.value = newQuery.level || ''
    selectedPrice.value = newQuery.price || ''
    sortBy.value = newQuery.sort || ''
    currentPage.value = parseInt(newQuery.page) || 1
    loadCourses()
  },
  { immediate: true }
)

onMounted(() => {
  loadCourses()
  loadCategories()
})
</script>

<style scoped>
.course-list-container {
  padding: 20px;
  background: #f0f8ff;
  min-height: calc(100vh - 140px);
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.filter-content {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  flex: 1;
}

.filter-group .el-select {
  width: 150px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  color: #2c5aa0;
  font-size: 24px;
  margin: 0;
}

.result-count {
  color: #606266;
  font-size: 14px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-group {
    width: 100%;
  }
  
  .filter-group .el-select {
    width: calc(50% - 8px);
  }
}
</style>